import tushare as ts
import pandas as pd
import sqlite3
import time
dbpath=  'D:/stockdata2021.db'
conn = sqlite3.connect(dbpath) #
#df = ts.get_tick_data('600581',date='2015-01-09')
#timedelta_range(start='1 days', periods=5, freq='D') timedelta_range(start='1 days', end='2 days', freq='30T')
#pd.period_range('201001','201005',freq='M')
#pd.TimedeltaIndex(['1 days', '1 days, 00:00:05', np.timedelta64(2,'D'), np.timedelta(days=2,seconds=2)])
def save_data(stock_code,date,src='sn'):
    try:
         detail = ts.get_tick_data(stock_code,date=str(date),src=src)

         time.sleep(1)
         if detail.shape[0]<1  :
             print(str(date)+'日无数据')
         else:
             print(detail)
             detail['oper_dt']=date
             detail['stock_code']=stock_code
             detail .to_sql('tp_stock_sh',conn,if_exists='append')
             print(str(date))
    except Exception as e:
        print(str(e))
        time.sleep(2)
        save_data(stock_code,date,src)
        
def get_by_code_dt(stock_code,start,end,src='sn'):
    conn.execute("drop table if exists tp_stock_sh")
    sql="""SELECT date  
            FROM stocks where code='{0}'  and date between '{1}' and '{2}'
            group by  date""".format(stock_code,start,end)
    dts=pd.read_sql(sql,conn)
    if dts.shape[0]>1:
        for i in dts.index:
            save_data(stock_code,str(dts.loc[i,'date']),src)
    else:
        for date in pd.period_range(start,end,freq='D'):
            save_data(stock_code,str(date),src)
 
if __name__ =='__main__':
    stockcode='000001'
    date='2019-06-01'
    #get_by_code_dt('sh','2019-01-01',date,'tt') 
    ts.set_token('995c6ed63737edf2f4140170a26fd598678478616b5ab45c4dcf9b27')

    df = ts.pro_bar(ts_code='sh',  start_date='20190101', end_date='20190511',freq='D',asset='I')
 